package com.xingji.caixia.upload;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.xingji.caixia.Constant;
import com.xingji.caixia.entitys.CardDao;
import com.xingji.caixia.entitys.UploadData;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zyh on 2017/9/29.
 */

public class Uploader implements Runnable{


    private BlockingQueue<UploadData> queue; //内存缓冲区

    private UploadData data;
    private Context context;

    private static AtomicInteger count = new AtomicInteger();// 总数 原子操作
    private static final int SLEEPTIME = 1000;


    public Uploader(BlockingQueue<UploadData> queue,UploadData data,Context context) {
        this.queue = queue;
        this.data = data;
        this.context = context;
    }

    @Override
    public void run() {
        this.uploadData(data);
    }


    /**
     * 上传数据
     * @param data
     */
    private void uploadData(final UploadData data){
        RequestParams requestParams = new RequestParams(Constant.UPLOAD_INFO);
        requestParams.addBodyParameter("card_no",data.getCard());
        requestParams.addBodyParameter("add_time", data.getTime().getTime()/1000 + "");
        requestParams.addBodyParameter("pic_url", new File(data.getImgPath()));
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                Log.e("result",result.toString());
                try {
                    data.setUploaded(true);
                    data.setResult(result.getString("content"));
                    if (result.getBoolean("status")){
                        data.setSad(true);//如果卡片有异常 还是记录一下
                    }
                    CardDao.update(data);
                    //// TODO: 2017/9/28 上传一个 通知data列表刷新
                    context.sendBroadcast(new Intent(Constant.HAS_READ));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }


}
